<template>
  <div class="app-container">
    <template>
      <div class="hidden-md-and-up">
        <el-alert title="如若不适应手机端操作，建议使用电脑操作" type="warning" />
      </div>
    </template>
    <div class="table-container">
      <div style="padding-bottom:20px; display: flex;">
        <div style="width: 200px;">
          <el-input v-model="search" size="medium" placeholder="输入关键字搜索" />
        </div>
        <div style="width: 220px; margin-left: 20px;">
          <label>项目类型</label>
          <el-select v-model="status1" size="medium" placeholder="请选择" style="width: 160px;" @change="statusChange">
            <el-option label="横向项目" value="横向项目" />
            <el-option label="纵向项目" value="纵向项目" />
          </el-select>
        </div>
        <div style="margin-left: 20px;" />
        <el-button type="success" size="medium" plain icon="el-icon-download" @click="excel_dialog = true">导出</el-button>
      </div>
      <el-table
        v-loading="paperListLoading"
        :data="paperList"
        element-loading-text="玩命加载中..."
        border
        fit
      >
        <el-table-column type="selection" align="center" width="55" />
        <!-- <el-table-column align="center" label="序号" width="55">
          <template slot-scope="scope">
            {{ scope.$index+1 }}
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="项目名称" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.projectName }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="承担单位" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.unit }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="项目负责人" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.head }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="项目总经费" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.projectTotalFunds }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="预算经费" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.projectTotalFunds }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="到账经费" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.arrivingFunds }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="支出经费" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.outputFunds }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="划拨经费" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.allocateFunds }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="130">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="open_infoview_dialog(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          background
          :current-page="p1_page"
          :page-sizes="[1,2,3,10, 20, 30, 40]"
          :page-size="p1_size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="p1_total"
          @size-change="p1_sizechange"
          @current-change="p1_currentchange"
        />
        <!-- @size-change="handleSizeChange"
          @current-change="handleCurrentChange" -->
        <!-- 使用了size-change和current-change事件来处理页码大小和当前页变动时候触发的事件。 -->
      </div>
      <el-dialog title="查看详情" :visible.sync="infoview_dialog" width="75%">
        <el-collapse v-model="activeNames">
          <el-collapse-item name="1">
            <template slot="title">
              <div class="el-descriptions__title">项目信息</div>
            </template>
            <el-descriptions :column="2" size="medium" border :label-style="{width:'25%'}" :content-style="{width:'25%'}">
              <el-descriptions-item label="横向项目ID">
                {{ infoview1.tregistrationID }}
              </el-descriptions-item>
              <el-descriptions-item label="录入人">
                {{ infoview1.entered }}
              </el-descriptions-item>
              <el-descriptions-item label="录入日期">
                {{ infoview1.enteredDate }}
              </el-descriptions-item>
              <el-descriptions-item label="项目名称">
                {{ infoview1.projectName }}
              </el-descriptions-item>
              <el-descriptions-item label="项目编号">
                {{ infoview1.projectId }}
              </el-descriptions-item>
              <el-descriptions-item label="项目类别">
                {{ infoview1.projectCate }}
              </el-descriptions-item>
              <el-descriptions-item label="项目来源单位">
                {{ infoview1.projectUnit }}
              </el-descriptions-item>
              <el-descriptions-item label="项目负责人">
                {{ infoview1.head }}
              </el-descriptions-item>
              <el-descriptions-item label="项目成员">
                {{ infoview1.projectMembers }}
              </el-descriptions-item>
              <el-descriptions-item label="项目状态">
                <el-tag :type="infoview1.projectState | statusFilter">{{ infoview1.projectState }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="项目开始日期">
                {{ infoview1.startTime }}
              </el-descriptions-item>
              <el-descriptions-item label="项目结束日期">
                {{ infoview1.endTime }}
              </el-descriptions-item>
              <el-descriptions-item label="立项日期">
                {{ infoview1.approvalTime }}
              </el-descriptions-item>
              <el-descriptions-item label="立项年度">
                {{ infoview1.approvalYear }}
              </el-descriptions-item>
              <el-descriptions-item label="档案编号">
                {{ infoview1.archiveNum }}
              </el-descriptions-item>
              <el-descriptions-item label="财务项目号">
                {{ infoview1.archiveNum }}
              </el-descriptions-item>
              <el-descriptions-item label="到校经费(万元)">
                {{ infoview1.arrivingFunds }}
              </el-descriptions-item>
              <el-descriptions-item label="合同经费(万元)">
                {{ infoview1.contractFunds }}
              </el-descriptions-item>
              <el-descriptions-item label="协作内容和要求">
                {{ infoview1.contentRequirements }}
              </el-descriptions-item>
              <el-descriptions-item label="预期成果(结题要求)">
                {{ infoview1.expect }}
              </el-descriptions-item>
              <el-descriptions-item label="预期目标和考核目标">
                {{ infoview1.goal }}
              </el-descriptions-item>
              <el-descriptions-item label="知识产权归属及分享">
                {{ infoview1.intellectual }}
              </el-descriptions-item>
              <el-descriptions-item label="工作进度计划">
                {{ infoview1.jobPlan }}
              </el-descriptions-item>
              <el-descriptions-item label="付款计划">
                {{ infoview1.payPlan }}
              </el-descriptions-item>
              <el-descriptions-item label="统计分类">
                {{ infoview1.classifi }}
              </el-descriptions-item>
              <el-descriptions-item label="承担单位">
                {{ infoview1.unit }}
              </el-descriptions-item>
              <el-descriptions-item label="出生年月">
                {{ infoview1.birthdate }}
              </el-descriptions-item>
              <el-descriptions-item label="职称">
                {{ infoview1.title }}
              </el-descriptions-item>
              <el-descriptions-item label="申请状态">
                <el-tag :type="infoview1.status | statusFilter">{{ infoview1.status }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="退回原因">
                {{ infoview1.reason }}
              </el-descriptions-item>
              <el-descriptions-item label="备注">
                {{ infoview1.notes }}
              </el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>
          <el-collapse-item name="2">
            <template slot="title">
              <div class="el-descriptions__title">成员列表</div>
            </template>
            <el-table
              v-loading="paperAuthorListLoading"
              :data="paperAuthorList"
              element-loading-text="Loading"
              border
              fit
            >
              <el-table-column type="selection" align="center" width="55" />
              <el-table-column align="center" label="姓名" min-width="100">
                <template slot-scope="scope">
                  {{ scope.row.name }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="所属院系" min-width="100">
                <template slot-scope="scope">
                  {{ scope.row.dept }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="署名单位" min-width="100">
                <template slot-scope="scope">
                  {{ scope.row.unit }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="排名" min-width="100">
                <template slot-scope="scope">
                  {{ scope.row.ranking }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="作者类型" min-width="100">
                <template slot-scope="scope">
                  {{ scope.row.authortype }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="作者类别" min-width="100">
                <template slot-scope="scope">
                  {{ scope.row.authorcate }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="考核系数" min-width="100">
                <template slot-scope="scope">
                  {{ scope.row.assessment }}
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
          <el-collapse-item name="3">
            <template slot="title">
              <div class="el-descriptions__title">附件信息</div>
            </template>
            <el-table
              v-loading="fileListLoading"
              :data="fileList"
              element-loading-text="Loading"
              border
              fit
            >
              <el-table-column type="index" align="center" width="55" />
              <el-table-column align="left" label="文件名称" min-width="150">
                <template slot-scope="scope">
                  {{ scope.row.filename }}
                </template>
              </el-table-column>
              <el-table-column align="left" label="文件大小" min-width="150">
                <template slot-scope="scope">
                  <span v-if="scope.row.filesize / 1024 / 1024 < 1">{{ (scope.row.filesize / 1024).toFixed(2) + 'KB' }}</span>
                  <span v-else>{{ (scope.row.filesize / 1024 / 1024).toFixed(2) + 'MB' }}</span>
                </template>
              </el-table-column>
              <el-table-column align="left" label="上传时间" min-width="150">
                <template slot-scope="scope">
                  {{ scope.row.filedate }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="150">
                <template slot-scope="scope">
                  <el-popover
                    :ref="`popoverdelete-${scope.$index}`"
                    placement="top"
                    width="160"
                  >
                    <p>确认删除本行吗？该操作不可撤销</p>
                    <div style="text-align: right; margin: 0">
                      <el-button size="mini" type="text" @click="scope._self.$refs[`popoverdelete-${scope.$index}`].doClose()">取消</el-button>
                      <el-button type="primary" size="mini" @click="deleteFile(scope.$index, scope.row)">确定</el-button>
                    </div>
                  </el-popover>
                  <el-button
                    size="mini"
                    @click="downloadFile(scope.row)"
                  >
                    下载
                  </el-button>
                  <el-button
                    v-popover="`popoverdelete-${scope.$index}`"
                    size="mini"
                    type="danger"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </el-collapse>
        <div slot="footer" class="dialog-footer">
          <el-button @click="infoview_dialog = false">关 闭</el-button>
        </div>
      </el-dialog>
      <el-dialog title="导出excel" :visible.sync="excel_dialog" width="60%">
        <el-alert
          title="请选择需要导出的数据"
          type="success"
          description="选择的数据为表头，未选择的数据将不会导出"
          :closable="false"
        />
        <div style="margin: 15px;">
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;" />
          <el-checkbox-group v-model="check_fields" @change="handleCheckedFieldsChange">
            <el-checkbox v-for="field in fields_list" :key="field" :label="field">{{ field }}</el-checkbox>
          </el-checkbox-group>
        </div>
        <el-alert
          title="请选择其他筛选条件"
          type="success"
          description="选择导出数据的筛选条件以及时间范围的信息，精准导出您所需要的信息"
          :closable="false"
        />
        <div style="padding-top:20px; display: flex;">
          <div style="width: 220px; margin-left: 20px;">
            <label>申请状态</label>
            <el-select v-model="status1" size="medium" placeholder="请选择" style="width: 160px;" @change="statusChange">
              <el-option label="全部" value="" />
              <el-option label="草稿" value="草稿" />
              <el-option label="待校审核" value="待校审核" />
              <el-option label="被校级退回" value="被校级退回" />
              <el-option label="审核通过" value="审核通过" />
            </el-select>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="excel_dialog = false">关 闭</el-button>
          <download-excel
            style="display:inline-block !important;margin-left:10px;"
            :data="EXCEL.DetailsForm"
            :fields="EXCEL.json_fields"
            :header="EXCEL.title"
            type="xls"
            name="我的横向项目导出数据.xls"
            :fetch="createExportData"
            :before-generate="startDownload"
            :before-finish="finishDownload"
          >
            <!-- 上面可以自定义自己的样式，还可以引用其他组件button -->
            <el-button type="success" plain>确认导出</el-button>
          </download-excel>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { get_thesis_author, get_file, file_add, file_delete } from '@/api/horizontal'
import { getMyPaperList } from '@/api/funds'
import { Message, Loading } from 'element-ui'
import { mapGetters } from 'vuex'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        草稿: 'info',
        待院审核: '',
        被院级退回: 'danger',
        待校审核: '',
        被校级退回: 'danger',
        审核通过: 'success',
        在研: 'success',
        结题: 'success',
        在研待院审核: '',
        在研待校审核: '',
        结题待院审核: '',
        结题待校审核: '',
        在研退回: 'danger',
        结题退回: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      search: '',
      infoview_dialog: false,
      visible1: false,
      visible2: false,
      paperList: [],
      paperListLoading: false,
      p1_size: 10,
      p1_total: 0,
      p1_page: 1,
      status1: '横向项目',
      paperAuthorList: [],
      paperAuthorListLoading: false,
      infoview1: {
        approvalMaterial: '',
        approvalTime: '',
        approvalYear: '',
        archiveNum: '',
        arrivingFunds: '',
        birthdate: '',
        classifi: '',
        contentRequirements: '',
        contractFunds: '',
        endTime: '',
        entered: '',
        enteredDate: '',
        expect: '',
        financialNum: '',
        goal: '',
        head: '',
        intellectual: '',
        jobPlan: '',
        notes: '',
        payPlan: '',
        projectCate: '',
        projectId: '',
        projectMembers: '',
        projectName: '',
        projectState: '',
        projectUnit: '',
        reason: '',
        startTime: '',
        status: '',
        title: '',
        tregistrationID: '',
        unit: ''
      },
      activeNames: ['1', '2', '3'],
      excel_dialog: false,
      all_fields: {
        'ID': 'tregistrationID',
        '录入人': 'entered',
        '录入日期': 'enteredDate',
        '项目名称': 'projectName',
        '项目编号': 'projectId',
        '项目类别': 'projectCate',
        '项目来源单位': 'projectUnit',
        '项目负责人': 'head',
        '项目成员': 'projectMembers',
        '项目状态': 'projectState',
        '项目开始日期': 'startTime',
        '项目结束日期': 'endTime',
        '立项日期': 'approvalTime',
        '立项年度': 'approvalYear',
        '档案编号': 'archiveNum',
        '财务项目号': 'financialNum',
        '到校经费(万元)': 'arrivingFunds',
        '合同经费(万元)': 'contractFunds',
        '协作内容和要求': 'contentRequirements',
        '预期成果(结题要求)': 'expect',
        '预期目标和考核目标': 'goal',
        '知识产权归属及分享': 'intellectual',
        '工作进度计划': 'jobPlan',
        '付款计划': 'payPlan',
        '统计分类': 'classifi',
        '承担单位': 'unit',
        '出生年月': 'birthdate',
        '职称': 'title',
        '申请状态': 'status',
        '退回原因': 'projectState',
        '备注': 'notes'
      },
      fields_list: [
        'ID',
        '录入人',
        '录入日期',
        '项目名称',
        '项目编号',
        '项目类别',
        '项目来源单位',
        '项目负责人',
        '项目成员',
        '项目状态',
        '项目开始日期',
        '项目结束日期',
        '立项日期',
        '立项年度',
        '档案编号',
        '财务项目号',
        '到校经费(万元)',
        '合同经费(万元)',
        '协作内容和要求',
        '预期成果(结题要求)',
        '预期目标和考核目标',
        '知识产权归属及分享',
        '工作进度计划',
        '付款计划',
        '统计分类',
        '承担单位',
        '出生年月',
        '职称',
        '申请状态',
        '退回原因',
        '备注'
      ],
      check_fields: [],
      checkAll: false,
      isIndeterminate: false,
      EXCEL: {
        title: '测试表格',
        json_fields: null,
        DetailsForm: null
      },
      fileList: [],
      fileListLoading: false
    }
  },
  computed: {
    ...mapGetters([
      'uid',
      'roles',
      'name'
    ]),
    MyPaperPost() {
      return {
        pageNum: this.p1_page,
        pageSize: this.p1_size,
        projectType: this.status1,
        projectName: this.search
      }
    }
  },
  watch: {
    search() {
      this.paperListLoading = true
      clearTimeout(this.searchTimeout) // 清除之前的定时器
      this.searchTimeout = setTimeout(() => {
        this.fetchPaperData()
        this.paperListLoading = false
      }, 1500) // 设置新的定时器，3秒后执行查询
    }
  },
  created() {
    this.fetchPaperData()
  },
  methods: {
    fetchPaperData() {
      this.paperListLoading = true
      getMyPaperList(this.MyPaperPost).then(response => {
        if (response.code === 200) {
          this.paperList = response.data.list
          this.p1_total = response.data.total
          this.paperListLoading = false
        }
      })
    },
    statusChange() {
      this.fetchPaperData()
    },
    p1_sizechange(newsize) {
      this.p1_size = newsize
      this.p1_page = 1
      this.fetchPaperData()
    },
    p1_currentchange(newpage) {
      this.p1_page = newpage
      this.fetchPaperData()
    },
    filterTag(value, row) {
      return row.status === value
    },
    resetForm(formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
    },
    fetch_thesis_author() {
      this.paperAuthorListLoading = true
      get_thesis_author(this.infoview1.tregistrationid).then(response => {
        if (response.code === 200) {
          this.paperAuthorList = response.data
          this.paperAuthorListLoading = false
        }
      })
    },
    open_infoview_dialog(row) {
      this.infoview_dialog = true
      this.infoview1 = JSON.parse(JSON.stringify(row))
      this.fetch_thesis_author()
      this.fetchFileData()
    },
    // 以下时数据导出
    handleCheckAllChange(val) {
      this.check_fields = val ? this.fields_list : []
      this.isIndeterminate = false
      this.EXCEL.json_fields = JSON.parse(JSON.stringify(this.all_fields, this.check_fields))
    },
    handleCheckedFieldsChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.fields_list.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.fields_list.length
      this.EXCEL.json_fields = JSON.parse(JSON.stringify(this.all_fields, this.check_fields))
    },
    async createExportData() {
      return await getMyPaperList(this.MyPaperPost).then(response => {
        if (response.code === 200) {
          if (response.data.list.length === 0) {
            Message.warning('返回数据为空，导出失败！')
            this.loadingInstance.close()
          }
          return response.data.list
        }
      })
    },
    startDownload() {
      this.excel_dialog = false
      this.loadingInstance = Loading.service({ text: '正在导出...' })
    },
    finishDownload() {
      setTimeout(() => {
        this.loadingInstance.close()
      }, 1000)
    },
    // 以下是附件上传
    handleFileSuccess(res, file, fileList) {
      console.log(file)
      this.fileForm.filename = file.name
      this.fileForm.filesize = file.size
      this.fileForm.fileurl = res.data
      this.commit_file()
    },
    commit_file() {
      file_add(this.fileForm).then(response => {
        if (response.code === 200) {
          Message.success('上传成功')
          this.fetchFileData()
        }
      })
    },
    fetchFileData() {
      this.fileListLoading = true
      get_file(this.infoview1.tregistrationID).then(response => {
        if (response.code === 200) {
          this.fileList = response.data
          this.fileListLoading = false
        }
      })
    },
    downloadFile(row) {
      var a = document.createElement('a')
      var event = new MouseEvent('click')
      a.href = row.fileurl
      a.target = '_blank'
      a.dispatchEvent(event)
    },
    deleteFile(index, row) {
      this.$refs[`popoverdelete-${index}`].doClose()
      file_delete(row.fileid).then(response => {
        if (response.code === 200) {
          Message.success('删除成功')
          this.fetchFileData()
        }
      })
    }
  }
}
</script>

<style lang="scss">
.el-form{
  margin-left: 40px;
  .el-input,.el-select{
    width: 300px;
  }
}
.el-tag + .el-tag {
  margin: 10px 10px;
}
.margin-top {
  margin-top: 50px;
}
@media screen and (max-width:600px) {
  .el-dialog{
    width: 100% !important;
  }
  .el-form{
    margin-left: 25px;
  }
}
</style>
